//
//  GSSubscribeViewController_Add_Topic_Details.m
//  GameSky
//
//  Created by lanou on 16/1/12.
//  Copyright © 2016年 NiRongfei. All rights reserved.
//

#import "GSSubscribeViewController_Add_Topic_Details.h"
#import "GSSubscribeViewController_Add_Topic_Details_Web.h"
#import "GSSubscribeViewController_Add_Topic_Details_Cell.h"
#import "GSSubscrebe_Add_Topic_Details.h"
#import "GSArticleViewController.h"
@interface GSSubscribeViewController_Add_Topic_Details () <UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>
// 展示视图
@property (nonatomic, strong) UITableView *tableView;
// 表头
@property (nonatomic, strong) UIImageView *imageV;
// 数据请求  起始index
@property (nonatomic, assign) NSInteger startIndex;
// 数据源数据
@property (nonatomic, strong) NSMutableArray *dataArray;
// 导航 bar
@property (nonatomic, strong) GSCustomNavigationBar *navigationBar;
// 显隐的 navigationView
@property (nonatomic, strong) UIView *navigationView;

/**
 * 数据库
 */
@property (nonatomic, strong) FMDatabase *db;
@end

@implementation GSSubscribeViewController_Add_Topic_Details
#pragma mark---------------视图将要出现--------------------
- (void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
}
#pragma mark---------------视图将要消失--------------------
- (void)viewWillDisappear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = NO;
}
#pragma mark---------------视图加载完成--------------------
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//  初始化 数据请求  起始点index
    _startIndex = 1;
// 初始化数据源数组
    self.dataArray = [NSMutableArray array];
// 添加 tableView
    [self addTableView];
// 数据请求
    [self setUpData];

// 添加 navigationView
    [self addNavigationView];
    // 添s加navigationBar
    [self addNavigationBar];
}
#pragma mark--------------添加navigationView-----------
- (void)addNavigationView{
    self.navigationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
    self.navigationView.backgroundColor = kRGBColor(0.81, 0.24, 0.2);
    _navigationView.alpha = 0;
    [self.view addSubview:_navigationView];
}
#pragma mark---------------添加navigationBar------------
- (void)addNavigationBar{
    self.navigationBar = [[GSCustomNavigationBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
    _navigationBar.backgroundColor = [UIColor clearColor];
    
    [_navigationBar.leftButton setImage:[UIImage imageNamed:@"common_Icon_Back_20x20_UIMode_Day@2x"] forState:(UIControlStateNormal)];
    
    
    [_navigationBar.leftButton addTarget:self action:@selector(leftButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
// 改变订阅按钮的 样式(判断是否被订阅过)
    [_navigationBar.rightButton setTitle:@"订阅" forState:(UIControlStateNormal)];
    [_navigationBar.rightButton setTitle:@"退订" forState:(UIControlStateSelected)];
    [_navigationBar.rightButton setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
    [_navigationBar.rightButton setTitleColor:[UIColor redColor] forState:(UIControlStateSelected)];
    _navigationBar.rightButton.backgroundColor = [UIColor whiteColor];
    if (self.isSubscribe) {
        _navigationBar.rightButton.selected = YES;
        _navigationBar.rightButton.backgroundColor = [UIColor clearColor];
    }
    // 添加点击方法
    [_navigationBar.rightButton addTarget:self action:@selector(rightButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    [self.view addSubview:_navigationBar];
}
// 点击方法
- (void)leftButtonAction:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

// 点击方法
- (void)rightButtonAction:(UIButton *)button{
    // 打开数据库
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    // 拼接路径
    NSString *pathString = [[path stringByAppendingPathComponent:@"data"]stringByAppendingPathComponent:@"GSDataBase.db"];
    _db = [FMDatabase databaseWithPath:pathString];
    if (![_db open]) {
        NSLog(@"数据打开失败");
    }

    
    button.selected = !button.selected;
    // 判断button的 选中 状态, 进行  插入(删除)数据库数据
    if (button.selected) {
        button.backgroundColor = [UIColor clearColor];
        
        if (![_db executeUpdate:@"insert into SubscribeList(nodeIds,cnt,sourceName,imageData) values(?,?,?,?)",self.model.sourceId,self.model.cnt,self.model.sourceName,self.imageData]) {
            NSLog(@"插入数据失败");
        }
    }else{
        button.backgroundColor = [UIColor whiteColor];
        
        // 非选中, 从数据库移除
        
        if (![_db executeUpdate:@"delete from SubscribeList where nodeIds = ?",self.model.sourceId]) {
            NSLog(@"删除数据失败");
            
        }
        
        
    }
}
#pragma mark---------------数据请求----------------------
- (void)setUpData{
    // 参数字典
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:self.dic];
    NSMutableDictionary *dictRequets = [NSMutableDictionary dictionaryWithDictionary:dict[@"request"]];
dictRequets[@"pageIndex"] = [NSString stringWithFormat:@"%ld",_startIndex];
    dict[@"request"] = dictRequets;
    
    
    
 [GSNetworkManager requestWithUrlStr:Subscribe_Add_Topic_Details paraDict:dict method:POST success:^(NSURLResponse *response, NSData *data) {
    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
// 获取 所需数据
    NSArray *array = dic[@"result"];
     if (_startIndex == 1) {
         [self.dataArray removeAllObjects];
     }
// 遍历, 给数据源数组  添加model
    for (NSDictionary *oneDic in array) {
        GSSubscrebe_Add_Topic_Details *model = [[GSSubscrebe_Add_Topic_Details alloc] init];
        [model setValuesForKeysWithDictionary:oneDic];
        
        [_dataArray addObject:model];
    }
// 给表头 图片
     if (_startIndex == 1) {
         GSSubscrebe_Add_Topic_Details *model = _dataArray[0];
         [_imageV sd_setImageWithURL:[NSURL URLWithString:model.thumbnailURLs[0]] placeholderImage:nil];
     }
    
// 刷新界面
     [self.tableView.mj_header endRefreshing];
     [self.tableView.mj_footer endRefreshing];
    [self.tableView reloadData];
 } failure:^(NSError *error) {
}];
}
#pragma mark---------------创建tableView-----------------
- (void)addTableView{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight) style:(UITableViewStylePlain)];
    // 夜间模式
    self.tableView.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
    _tableView.delegate = self;
    _tableView.dataSource = self;
// 添加表头
    _imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenWidth * 0.6)];
    _tableView.tableHeaderView = _imageV;
    
// 设置cell的高度
    _tableView.rowHeight = kScreenWidth * 0.225;
// 添加  刷新
    // 下拉
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _startIndex = 1;
        [self setUpData];
    }];
    // 上提
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _startIndex += 1;
        [self setUpData];
    }];
    [self.view addSubview:_tableView];
    
}
#pragma mark---------------tableView协议方法---------------
// 每个分区多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count - 1;
}
// 创建 Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = @"Cell";
    GSSubscribeViewController_Add_Topic_Details_Cell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[GSSubscribeViewController_Add_Topic_Details_Cell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
// 获取model
    GSSubscrebe_Add_Topic_Details *model = _dataArray[indexPath.row + 1];
    cell.model = model;
    return cell;
}
// cell点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
// 获取model
    GSSubscrebe_Add_Topic_Details *model = _dataArray[indexPath.row + 1];
//    GSSubscribeViewController_Add_Topic_Details_Web *webVC = [[GSSubscribeViewController_Add_Topic_Details_Web alloc] init];
//    
//    NSMutableDictionary *paraDict2 = [NSMutableDictionary dictionary];
//    paraDict2[@"deviceType"] = @"iPhone5,3";
//    paraDict2[@"deviceId"] = @"17E14E61-4069-4736-992D-EE596A7AECBC";
//    paraDict2[@"os"] = @"iOS";
//    paraDict2[@"osVersion"] = @"8.4";
//    paraDict2[@"app"] = @"GSApp";
//    paraDict2[@"appVersion"] = @"2.1.0";
//    paraDict2[@"request"] = @{@"contentId":model.contentId,
//                               @"pageIndex":@1};
//    
//    
//    webVC.dic = paraDict2;
    GSArticleViewController *articleVC = [[GSArticleViewController alloc] init];
    articleVC.contentID = model.contentId;
    [self.navigationController pushViewController:articleVC animated:YES];
}
#pragma mark---------------scrollView协议-----------------
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat y = scrollView.contentOffset.y;
       if (y > 0 && y < (kScreenWidth * 0.6 - 64)) {
        self.navigationView.alpha = y / (kScreenWidth * 0.6 - 64);
       }else if (y > (kScreenWidth * 0.6 - 64)){
           self.navigationView.alpha = 1;
       }
}
#pragma mark----------------------------------------------
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
